//
//  ImagePreviewVC.swift
//  sdxf
//
//  Created by 湛亚磊 on 2019/9/19.
//  Copyright © 2019 湛亚磊. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift
import Photos
//图片浏览控制器
open class ImagePreviewVC: UIViewController {
    
    //存储图片数组
    private var images:[String]
    
    //默认显示的图片索引
    private var index:Int
    
    private let disposeBag = DisposeBag()
    
    private lazy var topCustomBar: UIView = {
        let topCustomBar = UIView(frame: CGRect(x: 0, y: 0, width: ScreenW, height: NAVBAR_HEIGHT))
        topCustomBar.backgroundColor = .black
        let leftCloseButton=UIButton()
        leftCloseButton.size=CGSize(width: 30, height: 30)
        leftCloseButton.center=CGPoint(x: 32*PionWidth, y: NAVBAR_HEIGHT-37)
        leftCloseButton.setImage(UIImage(named: "预览返回"), for: .normal)
        leftCloseButton.tintColor = .white
        leftCloseButton.imageView?.contentMode = .scaleToFill
        leftCloseButton.rx.tap.subscribe(onNext: {[weak self] () in
            self?.dismiss(animated: true, completion: nil)
        }).disposed(by: disposeBag)
        topCustomBar.addSubview(leftCloseButton)
        ///添加 title
        topCustomBar.addSubview(titleLabel)
        titleLabel.center = CGPoint(x: UIScreen.main.bounds.width/2, y: leftCloseButton.center.y)
        return topCustomBar
    }()
    
    //collectionView的布局
    private lazy var collectionViewLayout: UICollectionViewFlowLayout = {
        //collectionView尺寸样式设置
        let collectionViewLayout = UICollectionViewFlowLayout()
        collectionViewLayout.minimumLineSpacing = 0
        collectionViewLayout.minimumInteritemSpacing = 0
        //横向滚动
        collectionViewLayout.scrollDirection = .horizontal
        return collectionViewLayout
    }()
    
    
    //用来放置各个图片单元
    private lazy var collectionView: UICollectionView = {
        //collectionView初始化
        let collectionView = UICollectionView(frame: CGRect(x: 0, y: NAVBAR_HEIGHT, width: ScreenW, height: ScreenH-NAVBAR_HEIGHT-44-MARGIN_BOTTOM),
                                          collectionViewLayout: collectionViewLayout)
        collectionView.backgroundColor = UIColor.black
        collectionView.register(ImagePreviewCell.self, forCellWithReuseIdentifier: "cell")
        collectionView.showsHorizontalScrollIndicator=false
        collectionView.showsVerticalScrollIndicator=false
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.isPagingEnabled = true
        //不自动调整内边距，确保全屏
        if #available(iOS 11.0, *) {
            collectionView.contentInsetAdjustmentBehavior = .never
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
        return collectionView
    }()
    ///底部的指示条
    private lazy var bottomControlView: UIView = {
        let bottomControlView = UIView(frame: CGRect(x: 0, y: ScreenH-44-MARGIN_BOTTOM, width: ScreenW, height: 44))
        bottomControlView.backgroundColor = .black
        bottomControlView.addSubview(indexLabel)
        return bottomControlView
    }()
    
    ///数量显示Label
    private lazy var indexLabel: UILabel = {
        let indexLabel = UILabel(frame: CGRect(x: ScreenW-90*PionWidth, y: 0, width: 75*PionWidth, height: 44))
        indexLabel.textColor = .white
        indexLabel.textAlignment = .right
        indexLabel.font = UIFont.systemFont(ofSize: 14)
        return indexLabel
    }()
    
    public lazy var heroView: UIView = {
        let heroView = UIView(frame: CGRect(x: 0, y: 0, width: ScreenW, height: ScreenH))
        heroView.isUserInteractionEnabled=true
        heroView.backgroundColor = .black
        return heroView
    }()
    
    
    //页控制器（小圆点）
    private lazy var pageControl: UIPageControl = {
        let pageControl = UIPageControl()
        pageControl.center = CGPoint(x: UIScreen.main.bounds.width/2,
                                     y: NAVBAR_HEIGHT-24)
        pageControl.currentPageIndicatorTintColor = .white
        pageControl.pageIndicatorTintColor = UIColor.RGB(r: 46, g: 46, b: 46)
        pageControl.numberOfPages = images.count
        pageControl.backgroundColor = .randomColor
        pageControl.isUserInteractionEnabled = false
        pageControl.isHidden=false
        pageControl.currentPage = index
        return pageControl
    }()
    
    public var hiddenPageControl:Bool = false{
        didSet{
            indexLabel.isHidden = hiddenPageControl
        }
    }
    
    public var hiddenCirclePageControl:Bool = true{
        didSet{
            pageControl.isHidden=hiddenCirclePageControl
        }
    }
    
    
    ///是否能保存图片
    public var isCanSavePhoto:Bool=false
    
    
    public var titleLabelInfo:String = ""{
        didSet{
            titleLabel.text=titleLabelInfo
        }
    }
    
    
    private lazy var titleLabel: UILabel = {
        let titleLabel = UILabel()
        titleLabel.isHidden=false
        titleLabel.font=UIFont.systemFont(ofSize: 16)
        titleLabel.textColor = .white
        titleLabel.size = CGSize(width: 100, height: 44)
        titleLabel.textAlignment = .center
        return titleLabel
    }()
    
    //初始化
    public init(images:[String], index:Int = 0){
        self.images = images
        self.index = index
        super.init(nibName: nil, bundle: nil)
    }
    
    public required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //初始化
    public override func viewDidLoad() {
        super.viewDidLoad()
        //背景设为黑色
        self.view.backgroundColor = UIColor.black
        self.view.addSubview(heroView)
        heroView.addSubview(topCustomBar)
        heroView.addSubview(collectionView)
        heroView.addSubview(bottomControlView)
        
        //将视图滚动到默认图片上
        let indexPath = IndexPath(item: (index-1), section: 0)
        collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
        indexLabel.text="\((index))/\(images.count)"
    }
    
    //视图显示时
    public override func viewWillAppear(_ animated: Bool) {
        //隐藏导航栏
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
    
    //视图消失时
    public override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    //隐藏状态栏
    public override var prefersStatusBarHidden: Bool {
        return false
    }
    
    //将要对子视图布局时调用（横竖屏切换时）
    public override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        
        //重新设置collectionView的尺寸
        collectionView.frame = CGRect(x: 0, y: NAVBAR_HEIGHT, width: ScreenW, height: ScreenH-NAVBAR_HEIGHT-44-MARGIN_BOTTOM)
        collectionView.collectionViewLayout.invalidateLayout()
        
        //将视图滚动到当前图片上
        let indexPath = IndexPath(item: (index-1), section: 0)
        collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
        
        //重新设置页控制器的位置
        bottomControlView.frame=CGRect(x: 0, y: ScreenH-44-MARGIN_BOTTOM, width: ScreenW, height: 44)
//        pageControl.center = CGPoint(x: UIScreen.main.bounds.width/2,
//                                     y: UIScreen.main.bounds.height - 20)
    }
    
    public override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

//ImagePreviewVC的CollectionView相关协议方法实现
extension ImagePreviewVC:UICollectionViewDelegate, UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout{
    
    //collectionView单元格创建
    public func collectionView(_ collectionView: UICollectionView,
                        cellForItemAt indexPath: IndexPath)
        -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell",
                                                          for: indexPath) as! ImagePreviewCell
            let imageName = self.images[indexPath.row]
            
            if let goodPhotoUrl=URL(string: imageName){
                cell.imageView.kf.setImage(with: goodPhotoUrl)
            }
            if isCanSavePhoto{
                cell.postSvaeImageBlock {[weak self] (image) in
                    DispatchQueue.main.async {
                        //code
                        self?.saveImage(with: image)
                    }
                }
            }
            return cell
    }
    
    private func saveImage(with image:UIImage) {
        
        let alter=UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        let shureAction = UIAlertAction(title: "保存图片", style: .default) {[weak self](action) in
            ///保存照片
            QXManager.photoAlbumPermissions(authorizedBlock: {
                ToastView.instance.showLoadingView()
                PHPhotoLibrary.shared().performChanges({
                        PHAssetChangeRequest.creationRequestForAsset(from: image)
                    }) { (isSuccess, error) in
                        DispatchQueue.main.async {
                            ToastView.instance.clear()
                            if isSuccess {
                                ToastView.instance.showToast(content: "保存成功")
                            } else {
                                /// 图片保存失败了
                            }
                    }
                }
            }) {[weak self] in
                ///权限
                let cancleAction = UIAlertAction(title: "确认", style: .default, handler: { action in
                })
                ///取消
                let settingAction = UIAlertAction(title: "去设置", style: .default, handler: { action in
                    UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options:[:], completionHandler: nil)
                })
                ///弹窗
                let alertController = UIAlertController(title: "无访问权限", message: "请在手机的「设置-隐私-照片」选项中，允许先防时代访问您的照片", preferredStyle: .alert).then {
                    $0.addAction(cancleAction)
                    $0.addAction(settingAction)
                }
                self?.navigationController?.present(alertController, animated: true, completion:nil)
            }
        }
        let cancleAction = UIAlertAction(title: "取消", style: .cancel) { (action) in
        }
        alter.addAction(cancleAction)
        alter.addAction(shureAction)
        self.present(alter, animated: true, completion: nil)
    }
    
    
    //collectionView单元格数量
    public func collectionView(_ collectionView: UICollectionView,
                        numberOfItemsInSection section: Int) -> Int {
        return self.images.count
    }
    
    //collectionView单元格尺寸
    public func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: ScreenW, height: ScreenH-NAVBAR_HEIGHT-44-MARGIN_BOTTOM)
    }
    
    //collectionView里某个cell将要显示
    public func collectionView(_ collectionView: UICollectionView,
                        willDisplay cell: UICollectionViewCell,
                        forItemAt indexPath: IndexPath) {
        if let cell = cell as? ImagePreviewCell{
            //由于单元格是复用的，所以要重置内部元素尺寸
            cell.resetSize()
        }
    }
    
    //collectionView里某个cell显示完毕
    public func collectionView(_ collectionView: UICollectionView,
                        didEndDisplaying cell: UICollectionViewCell,
                        forItemAt indexPath: IndexPath) {
        //当前显示的单元格
        let visibleCell = collectionView.visibleCells[0]
        indexLabel.text="\(collectionView.indexPath(for: visibleCell)!.item+1)/\(images.count)"
        //设置页控制器当前页
        self.pageControl.currentPage = collectionView.indexPath(for: visibleCell)!.item
    }
    
    
}
